﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace iToolPlugin.SMSProvider
{
    public class DefaultHTTPClient : IHTTPClient
    {
        public HTTPResponse fetch(HTTPRequest request)
        {
            UriBuilder uriBuilder = new UriBuilder(request.url);
            StringBuilder stringBuilder = new StringBuilder();
            foreach (KeyValuePair<string, string> parameter in request.parameters)
            {
                stringBuilder.Append(parameter.Key);
                stringBuilder.Append("=");
                stringBuilder.Append(parameter.Value);
                stringBuilder.Append("&");
            }

            stringBuilder.Length--;
            uriBuilder.Query = stringBuilder.ToString();
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.RequestUri = uriBuilder.Uri;
            request.url = uriBuilder.Uri.ToString();
            httpRequestMessage.Method = new HttpMethod(request.method.ToString());
            httpRequestMessage.Content = new StringContent(request.body, request.bodyEncoding);
            foreach (KeyValuePair<string, string> header in request.headers)
            {
                if (header.Key == "Content-Type")
                {
                    httpRequestMessage.Content!.Headers.ContentType = new MediaTypeHeaderValue(header.Value);
                }
                else
                {
                    httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    HttpResponseMessage result = httpClient.SendAsync(httpRequestMessage).Result;
                    string result2 = result.Content.ReadAsStringAsync().Result;
                    HTTPResponse hTTPResponse = new HTTPResponse().setRequest(request).setStatusCode((int)result.StatusCode).setReason(result.ReasonPhrase)
                        .setBody(result2);
                    foreach (KeyValuePair<string, IEnumerable<string>> header2 in result.Headers)
                    {
                        foreach (string item in header2.Value)
                        {
                            hTTPResponse.addHeader(header2.Key, item);
                        }
                    }

                    return hTTPResponse;
                }
                catch (HttpRequestException)
                {
                    throw;
                }
            }
        }

        public void close()
        {
        }
    }
}
